import 'dart:math';

import 'package:chewie/chewie.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_barrage/flutter_barrage.dart';
import 'package:flutter_frame/app/components/toast_widget.dart';
import 'package:flutter_frame/app/core/core.dart';
import 'package:flutter_frame/app/core/values/colors.dart';
import 'package:flutter_frame/app/core/values/dimens.dart';
import 'package:flutter_frame/app/core/values/gaps.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:video_player/video_player.dart';

/// 指挥调度
class Dispatch extends StatefulWidget {
  const Dispatch({super.key});

  @override
  State<Dispatch> createState() => _DispatchState();
}

class _DispatchState extends State<Dispatch> {
  late ValueNotifier<BarrageValue> timelineNotifier;
  late VideoPlayerController videoPlayerController;
  late BarrageWallController barrageWallController;
  late ChewieController chewieController;

  // 弹幕输入框控制器
  TextEditingController barrageController = TextEditingController();

  // 发送弹幕
  void sendBarrage() async {
    if (barrageController.text.isNotEmpty) {
      // 关闭键盘
      FocusScope.of(context).requestFocus(FocusNode());
      AppToast.showSuccess('发送成功');
      barrageWallController.send([
        Bullet(
            child: Text(
          barrageController.text,
          style: const TextStyle(
            color: Colors.red,
          ),
        ))
      ]);
      barrageController.clear();
    }
  }

  // 初始化弹幕信息
  void initBarrage() {
    timelineNotifier = ValueNotifier(BarrageValue());
    videoPlayerController = VideoPlayerController.networkUrl(Uri.parse(
      'https://media.w3.org/2010/05/sintel/trailer.mp4',
    ))
      ..addListener(() {
        timelineNotifier.value = timelineNotifier.value.copyWith(
          timeline: videoPlayerController.value.position.inMilliseconds,
          isPlaying: videoPlayerController.value.isPlaying,
        );
      });
    barrageWallController = BarrageWallController(timelineNotifier: timelineNotifier);

    final Random random = Random();
    final List<Bullet> bullets = List<Bullet>.generate(200, (i) {
      final showTime = random.nextInt(1 * 60 * 1000);
      return Bullet(
        showTime: showTime,
        child: Text(
          '弹幕$i',
          style: const TextStyle(color: Colors.white),
        ),
        // child: IgnorePointer(child: Text('$i-$showTime')),
      );
    });
    chewieController = ChewieController(
      videoPlayerController: videoPlayerController,
      aspectRatio: 16 / 9,
      autoPlay: true,
      looping: true,
      overlay:  LayoutBuilder(builder: (context,BoxConstraints constraints) {
        debugPrint('overlay: ${constraints.maxWidth} ${constraints.maxHeight}');
        // 重新初始化 BarrageWallController
        // barrageWallController.clear();
        barrageWallController = BarrageWallController(timelineNotifier: timelineNotifier);
        if (constraints.maxWidth > constraints.maxHeight) {
          return BarrageWall(
            width: constraints.maxWidth,
            height: constraints.maxHeight,
            // debug: true,
            // do not send bullets to the safe area
            safeBottomHeight: 60,
            // speed: 8,
            massiveMode: false,
            speedCorrectionInMilliseconds: 5000,
            controller: barrageWallController,
            timelineNotifier: timelineNotifier,
            bullets: bullets,
            child: Container(),
          );
        } else {
          return Container(
            alignment: Alignment.center,
            child: const Text('草泥马'),
          );
        }
      }),
    );
  }

  // 弹幕开关
  void barrageSwitch() {
    barrageWallController.isEnabled ? barrageWallController.disable() : barrageWallController.enable();
    setState(() {});
  }

  @override
  void initState() {
    super.initState();
    initBarrage();
  }

  @override
  void dispose() {
    timelineNotifier.dispose();
    barrageController.dispose();
    barrageWallController.dispose();
    videoPlayerController.dispose();
    chewieController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        SizedBox(
          height: 220.w,
          child: Chewie(
            controller: chewieController,
          ),
        ),
        Container(
          height: AppDimens.dp54,
          color: const Color(0x1A5C6DFF),
          child: Row(
            children: [
              AppGaps.hGap16,
              Text(
                '弹幕',
                style: TextStyle(
                  fontSize: 15.sp,
                ),
              ),
              SizedBox(
                height: 12,
                child: CupertinoSwitch(
                  value: barrageWallController.isEnabled,
                  activeColor: AppColors.primary_color,
                  onChanged: (value) {
                    barrageSwitch();
                  },
                ),
              ),
              AppGaps.hGap16,
              Expanded(
                child: Container(
                    height: 32.w,
                    padding: EdgeInsets.symmetric(horizontal: 12.w),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        color: Colors.white,
                        border: Border.all(color: const Color(0xffF0F0F0), width: 1.w),
                        borderRadius: BorderRadius.all(Radius.circular(8.w))),
                    child: Row(
                      children: [
                        Expanded(
                            child: TextField(
                                keyboardType: TextInputType.text,
                                textInputAction: TextInputAction.send,
                                controller: barrageController,
                                onSubmitted: (value) {
                                  sendBarrage();
                                },
                                style: TextStyle(color: const Color(0xff222222), fontWeight: FontWeight.w400, fontSize: 14.sp),
                                decoration: InputDecoration(
                                  counterText: '',
                                  //防止适配不居中
                                  isCollapsed: true,
                                  border: const OutlineInputBorder(borderSide: BorderSide.none),
                                  contentPadding: EdgeInsets.only(left: 8.w),
                                  hintText: '请输入弹幕内容',
                                  hintStyle: TextStyle(fontSize: 14.sp, fontWeight: FontWeight.w400, color: const Color(0xffA0A7B5)),
                                  suffix: GestureDetector(
                                    onTap: sendBarrage,
                                    child: Text(
                                      '发送',
                                      style: TextStyle(fontSize: 14.sp, fontWeight: FontWeight.w400, color: Colors.blue),
                                    ),
                                  ),
                                )))
                      ],
                    )),
              ),
              AppGaps.hGap16,
            ],
          ),
        ),
        Expanded(
          child: RefreshIndicator(
            onRefresh: () async {},
            child: ListView.separated(
              padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 10.w),
              itemCount: 40,
              itemBuilder: (context, index) {
                return Column(
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text('张三',
                            style: TextStyle(
                              fontSize: 14.sp,
                              color: const Color(0xffA0A7B5),
                            )),
                        Text('2021-08-12 12:00:00',
                            style: TextStyle(
                              fontSize: 12.sp,
                              color: const Color(0xffA0A7B5),
                            ))
                      ],
                    ),
                    SizedBox(
                      height: 5.w,
                    ),
                    Align(
                      alignment: Alignment.centerLeft,
                      child: Text('这是一条弹幕',
                          style: TextStyle(
                            fontSize: 14.sp,
                            color: const Color(0xff222222),
                          )),
                    )
                  ],
                );
              },
              separatorBuilder: (context, index) {
                return Container(
                  height: 1.w,
                  margin: const EdgeInsets.only(
                    top: 16,
                    bottom: 16,
                  ),
                  color: Colors.grey.withOpacity(0.2),
                );
              },
            ),
          ),
        )
      ],
    );
  }
}
